package cn.gjxblog.aop.proxy.spring.demo1;

import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

/**
 * 使用ProxyFactory创建代理，可以脱离IOC
 */
public class TestProxyFactory {
    public static void main(String[] args) {
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(new UserServiceImpl());
        proxyFactory.setInterfaces(UserService.class);

        //只设置通知
//        demo1(proxyFactory);
        //通过切面方式执行
        demo2(proxyFactory);

        UserService proxy = (UserService) proxyFactory.getProxy();
        proxy.getUser(2);
        
    }

    private static void demo2(ProxyFactory proxyFactory) {
        // 生命一个
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* cn.gjxblog.aop.proxy.spring.demo1.*.*(..))");
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, new MyMethodInterceptor());
        proxyFactory.addAdvisor(advisor);
    }

    private static void demo1(ProxyFactory proxyFactory) {
        // 设置Advice
        proxyFactory.addAdvice(new MyAfterReturningAdvice());
        proxyFactory.addAdvice(new MyAfterThrowsAdvice());
        proxyFactory.addAdvice(new MyMethodBeforeAdvice());
        //环绕通知
        proxyFactory.addAdvice(new MyMethodInterceptor());


    }
}
